package com.verlet.configclient.message;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;

import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 *
 * @author verlet
 * @date 2019/5/7
 */
@Slf4j
@Component
@EnableBinding(Barista.class)
public class StreamReceiver {

    @Autowired
    private Barista barista;

    /**
     * 消息发送
     */
    public void send(String message, Map<String, Object> properties) {
        MessageHeaders messageHeaders = new MessageHeaders(properties);
        Message<String> msg = MessageBuilder.createMessage(message, messageHeaders);
        barista.output().send(msg);
        log.info("StreamReceiver-send:{}", message);
    }

    /**
     * 消息接收
     */
    @StreamListener(Barista.INPUT_CHANNEL)
    public void receive(Message<String> message) throws IOException {
        Channel channel = (Channel) message.getHeaders().get(AmqpHeaders.CHANNEL);
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        log.info("StreamReceiver-receive:{}", message.getPayload());
        channel.basicAck(deliveryTag,false);
    }

}
